package com.training.net;

import com.google.gson.Gson;

import java.io.IOException;


import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class NetCallback<T> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            onSuccess(response.body());
        } else {
            ResponseBody errorBody = response.errorBody();
            if (errorBody != null) {
                try {
                    // 手动将errorBody转换为字符串
                    String errorBodyString = errorBody.string();
                    // 使用Gson等库解析
                    Gson gson = new Gson();
                    HttpResponse errorResponse = gson.fromJson(errorBodyString, HttpResponse.class);
                    // 现在可以访问code和message
                    int code = errorResponse.code;
                    String message = errorResponse.message;
                    onError(code, message);
                } catch (IOException e) {
                    e.printStackTrace();
                    onError(response.code(), response.message());
                }
            }else {
                onError(response.code(), response.message());
            }
        }
        onFinally();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        onError(0, t.getMessage());
        onFinally();
    }

    abstract public void onError(int code, String message);

    abstract public void onSuccess(T response);
    abstract public void onFinally();
}
